package cn.school.mybatis.controller;

import cn.school.mybatis.pojo.Grade;
import cn.school.mybatis.pojo.Student;
import cn.school.mybatis.service.GradeService;
import cn.school.mybatis.service.StudentService;
import cn.school.mybatis.util.DateUtil;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/s_student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private GradeService gradeService;

    //分页查询
    @RequestMapping("/searchStudent")
    public ModelAndView searchStudent(@ModelAttribute @RequestParam Map map,
                                      @RequestParam(value = "pageNo",defaultValue = "1") int pageNo,
                                      @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
//        map.put("dateStart", DateUtil.toDate(String.valueOf(map.get("dateStart"))));
//        map.put("dateEnd", DateUtil.toDate(String.valueOf(map.get("dateEnd"))));
//        map.put("pageNo", pageNo);
//        map.put("pageSize", pageSize);
        System.out.println("初始map"+map);
//        map.put("pageNo", Integer.valueOf((String) map.get("pageNo")));
//        map.put("pageSize", Integer.valueOf((String) map.get("pageSize")));
//        System.out.println("二次map"+map);
        map.remove("pageNo");
        map.remove("pageSize");
        System.out.println("移除map"+map);

        ModelAndView mv=new ModelAndView();

        //获得符合条件的学生表
        List<Student> lists = studentService.search(pageNo, pageSize, map);
        //总条数
        double pageTotal = studentService.findTotal(map);
        //总页数
        int pageNum = (int) Math.ceil(pageTotal / pageSize);

        //学生获取年级名称
        List<Grade> gradeList = gradeService.searchAll();
        Map gradeMap=new HashMap();
        for (Grade g:gradeList){
            int id= (int) g.getId();
            String gname=g.getGname();
            gradeMap.put(id,gname);
        }
        for (Student stu:lists){
            stu.setGname((String) gradeMap.get(stu.getGradeid()));
        }

        mv.addObject("pageNo", pageNo);
        mv.addObject("pageSize", pageSize);
        mv.addObject("pageTotal", (int) pageTotal);
        mv.addObject("pageNum", pageNum);
        mv.addObject("stuLists", lists);
        mv.addObject("sname", map.get("sname"));
        mv.addObject("telephone", map.get("telephone"));

        mv.setViewName("school/s_student/searchStudent");
        return mv;
    }

    //Ajax分页查询
    @RequestMapping(value = "/ajaxSearchStudent",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String ,Object> ajaxSearchStudent(@ModelAttribute @RequestParam Map map,
                                      @RequestParam(value = "pageNo",defaultValue = "1") int pageNo,
                                      @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        System.out.println("初始map"+map);
        map.remove("pageNo");
        map.remove("pageSize");
//        map.put("pageNo",Integer.parseInt((String) map.get("pageNo")));
//        map.put("pageSize",Integer.parseInt((String) map.get("pageSize")));
        System.out.println("移除数据后map"+map);

        //获得符合条件的学生表
        List<Student> lists = studentService.search(pageNo, pageSize, map);
        //总条数
        double pageTotal = studentService.findTotal(map);
        //总页数
        int pageNum = (int) Math.ceil(pageTotal / pageSize);

        //学生获取年级名称
        List<Grade> gradeList = gradeService.searchAll();
        Map gradeMap=new HashMap();
        for (Grade g:gradeList){
            int id= (int) g.getId();
            String gname=g.getGname();
            gradeMap.put(id,gname);
        }
        for (Student stu:lists){
            stu.setGname((String) gradeMap.get(stu.getGradeid()));
        }

        Map<String, Object> ajaxMap= new HashMap<>();

        ajaxMap.put("pageNo", pageNo);
        ajaxMap.put("pageSize", pageSize);
        ajaxMap.put("pageTotal", (int) pageTotal);
        ajaxMap.put("pageNum", pageNum);
        ajaxMap.put("stuDatas", lists);
        ajaxMap.put("sname", map.get("sname"));
        ajaxMap.put("telephone", map.get("telephone"));
        ajaxMap.put("gradeid", map.get("gradeid"));
        ajaxMap.put("wechat", map.get("wechat"));

        return ajaxMap;
    }

    //增加学生
    @RequestMapping(method = RequestMethod.POST,value = "addStudent")
     public void addStudent(@Valid Student student ,
                            HttpServletRequest req,
                            HttpServletResponse resp,
                            //BindingResult bindingResult,
                            @RequestPart(value = "photo",required = false) MultipartFile multipartFile ) throws IOException {
        System.err.println("新增的学生信息:"+student+"上传文件信息："+multipartFile);
        if (!multipartFile.isEmpty()) {
            String path = req.getServletContext().getRealPath("static" + File.separator + "images");
            System.err.println("获得的文件夹路径:" + path);
            String fName = multipartFile.getOriginalFilename();
            String houZhui = fName.substring(fName.lastIndexOf("."));
            String fileName = UUID.randomUUID() + houZhui;
            File file = new File(path, fileName);
            System.err.println("路径：" + path + ",名称：" + fileName);
            if (!file.exists()) {
                file.mkdirs();     //判断这个文件是否存在
            }
            student.setIdcardpic(fileName);
            try {
                multipartFile.transferTo(file);// 将上传文件保存到相应位置
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        resp.setContentType("text/html;charset=utf-8");
        if (studentService.add(student)>0){
            resp.getWriter().println("<script>alert('学生增加成功！');location.replace('searchStudent');</script>");
        }else {
            resp.getWriter().println("<script>alert('学生增加失败！');history.back();</script>");
        }

     }

    //删除学生
     @RequestMapping("/delStudent")
    public void delStudent(int stuno,HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        if (studentService.delete(stuno)>0){
            resp.getWriter().println("<script>alert('学生删除成功！');location.replace('searchStudent');</script>");
        }else {
            resp.getWriter().println("<script>alert('学生删除失败！');history.back();</script>");
        }

    }

    //去分页查询页
    @RequestMapping("/toSearchStudent")
    public String toSearchStudent() {
        return "school/s_student/searchStudent";
    }

    //去增加学生页
    @RequestMapping("/toAddStudent")
    public String toAddStudent() {
        return "school/s_student/addStudent";
    }

    //去展示一个学生页
    @RequestMapping("/toShowStudent/{stuno}")
    public ModelAndView toShowStudent(@PathVariable int stuno,HttpServletResponse resp) throws IOException {
        ModelAndView mv=new ModelAndView();
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Student student = studentService.get(stuno);
        if (student == null) {
            out.print("<script>alert('未找到相关信息！');history.back();</script>");
        }
        //年级名称
        String gradeName=gradeService.get(student.getGradeid()).getGname();

        mv.addObject("student",student);
        mv.addObject("gradeName",gradeName);
        mv.setViewName("school/s_student/showStudent");
        return mv;
    }

    //去更新学生页
    @RequestMapping("/toUpdateStudent")
    public ModelAndView toUpdateStudent(int stuno,HttpServletResponse resp) throws IOException {
        ModelAndView mv=new ModelAndView();
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Student student = studentService.get(stuno);
        //年级名称
        List<Grade> lists = gradeService.searchAll();

        if (student == null) {
            out.print("<script>alert('未找到相关信息！');history.back();</script>");
        }
        //年级名称
        String gradeName=gradeService.get(student.getGradeid()).getGname();

        mv.addObject("student",student);
        mv.addObject("gradeName",gradeName);
        mv.addObject("gradeLists",lists);

        mv.setViewName("school/s_student/updateStudent");
        return mv;
    }

    //更新学生操作
    @RequestMapping("/doUpdateStudent")
    public void doUpdateStudent(@ModelAttribute Student student,HttpServletRequest req,HttpServletResponse resp,@RequestPart(value = "photo",required = false) MultipartFile multipartFile) throws Exception {
        System.out.println("修改后的学生信息:"+student);
        if (!multipartFile.isEmpty()) {
            String path = req.getServletContext().getRealPath("static" + File.separator + "images");
            System.err.println("获得的文件夹路径:" + path);
            String fName = multipartFile.getOriginalFilename();
            String houZhui = fName.substring(fName.lastIndexOf("."));
            String fileName = UUID.randomUUID() + houZhui;
            File file = new File(path, fileName);
            System.err.println("路径：" + path + ",名称：" + fileName);
            if (!file.exists()) {
                file.mkdirs();     //判断这个文件是否存在
            }
            student.setIdcardpic(fileName);
            try {
                multipartFile.transferTo(file);// 将上传文件保存到相应位置
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        resp.setContentType("text/html;charset=utf-8");
        if (studentService.update(student)>0){
            resp.getWriter().println("<script>alert('学生修改成功！');location.replace('searchStudent');</script>");
        }else {
            resp.getWriter().println("<script>alert('学生修改失败！');history.back();</script>");
        }
    }

    //获得所有年级信息
    @RequestMapping("/getGrade")
    public void gerGrade(HttpServletResponse resp) throws IOException {
        List<Grade> list = gradeService.searchAll();
        String gradeJSON= JSON.toJSONString(list);
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().print(gradeJSON);
    }

    //检查微信是否重复
    @RequestMapping("/checkWechat")
    @ResponseBody
    public boolean checkWechat( String wechat){
        return  this.studentService.findWechat(wechat);
    }


    //检查电话是否重复
    @RequestMapping("/checkTele")
    @ResponseBody
    public boolean checkTelephone(String telephone){
        return  this.studentService.findTel(telephone);
    }



    //局部异常处理：本类产生的异常
//    @ExceptionHandler
//    public String exceptionHandler(Exception e){
//        e.printStackTrace();
//        return "error500";
//    }

}
